#!/usr/bin/env python2

##
## Copyright (C) 2011 Luciano Xumerle <luciano.xumerle@gmail.com>
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.
##

import sys

def illumina2fastq( illuminaFile, rmidx, startline ):
   """Converts illumina file to fastq. Each line is printed to standard output"""
   chiocciola = startline
   conversion=dict()
   for a in range(0,225):
       conversion[ chr(a+31) ] = chr( a )
   counter=0
   fh=sys.stdin
   if illuminaFile != '-':
        fh = open(illuminaFile, "r")
   for line in fh:
       line=line.strip()
       counter=counter+1
       if counter == 1:
           line = chiocciola + line[1:]
           if rmidx:
               line = line[:line.rindex('#')] + line[line.rindex('/'):]

       if counter == 3:
           line = "+"

       elif counter == 4:
           counter=0
           qual=line
           line=""
           for i in qual:
               line = line + conversion[i]
       print line


def printHelp():
   errorMsg="SYNTAX:\n " + sys.argv[0] + " [-rmidx] [-useat] <illuminafile>\n\n Use '-' as filename to read sequences from STDIN\n"
   print >>sys.stderr, errorMsg


def main():
   rmidx=False
   fastqsequencestart=">"
   inputfile=""

   if len(sys.argv)<2:
       printHelp()
       return

   for a in sys.argv[1:]:
       if a == "-rmidx":
           rmidx=True
       if a == "-useat":
           fastqsequencestart="@"
       else:
           inputfile=a
   illumina2fastq( inputfile, rmidx, fastqsequencestart )

if __name__ == "__main__":
   main()
